package org.example.freeswitchdemo.listener;

import org.freeswitch.esl.client.IEslEventListener;
import org.freeswitch.esl.client.inbound.Client;
import org.freeswitch.esl.client.transport.event.EslEvent;
import org.freeswitch.esl.client.transport.message.EslMessage;

//@Component
public class FreeswitchEventListener {

    private final Client eslClient;

    public FreeswitchEventListener(Client eslClient) {
        this.eslClient = eslClient;
    }

//    @PostConstruct
    public void init() {
        // 订阅 FreeSWITCH 全部事件，也可以只订阅 CHANNEL_* 事件
        eslClient.addEventListener(new IEslEventListener() {
            @Override
            public void eventReceived(EslEvent event) {
                System.out.println("📢 收到事件: " + event.getEventName());

                // 打印一些常见字段
                String uuid = event.getEventHeaders().get("Unique-ID");
                String caller = event.getEventHeaders().get("Caller-Caller-ID-Number");
                String callee = event.getEventHeaders().get("Caller-Destination-Number");

                System.out.println("   ➡️ UUID: " + uuid);
                System.out.println("   📞 主叫: " + caller + " → 被叫: " + callee);
            }

            @Override
            public void backgroundJobResultReceived(EslEvent event) {
                System.out.println("✅ 收到后台任务结果: " + event.getEventHeaders());
            }
        });

        // 告诉 FreeSWITCH 我们要订阅的事件
        EslMessage response = eslClient.sendSyncApiCommand("event", "ALL");
        System.out.println("订阅事件结果: " + response.getBodyLines());
    }
}

